import axios from 'axios'
import {
	netConfig
} from '@/config/net.config.js'
import {
	hasKey,
	handleStreamData
} from '@/utils/tools.js'
const {
	baseURL,
	contentType,
	requestTimeout,
	successCode,
	failCode,
	statuKeys,
	msgKeys
} = netConfig;
const instance = axios.create({
	baseURL,
	timeout: requestTimeout,
	headers: {
		'Content-Type': contentType,
	},
});
let tokenLose = true;
// request interceptor
instance.interceptors.request.use(
	(config) => {
		// do something before request is sent
		return config;
	},
	(error) => {
		// do something with request error
		console.log(error);
		return Promise.reject(error);
	}
);

// response interceptor
instance.interceptors.response.use(
	/**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	 */
	(response) => {
		console.log(response);
		const res = response.data;
		// 请求出错处理
		// -1 超时、token过期或者没有获得授权
		const statuKey = hasKey(res, statuKeys)
		const msgKey = hasKey(res, msgKeys)
		if (failCode.indexOf(res[statuKey]) !== -1 && tokenLose) {
			tokenLose = false;
			uni.showToast({
				title: res[msgKey],
				icon: 'error',
				duration: 2000
			});

			return Promise.reject(res);
		}
		if (successCode.indexOf(res.status) !== -1) {
			return Promise.reject(res);
		}
		return res;
	},
	(error) => {
		console.log(error);
		uni.hideLoading()
		let msgKey = ''
		let res = {}
		if (error.request.responseType === 'arraybuffer' && error.response) {
			res = handleStreamData(error.response.data)

		} else {
			res = error.response.data
		}
		msgKey = hasKey(res, msgKeys)
		//是否错误弹框判断
		if (!error.config.disErrMsg) {
			uni.showToast({
				title: res[msgKey],
				icon: 'error',
				duration: 2000
			});
		}
		return Promise.reject(error);
	}
);

export default instance;